import java.text.SimpleDateFormat;
import java.util.*;

public class Manager extends User {

    public Manager(String ID, String password, String name, String date, String tel) {
        super(ID, password, name, date, tel);
        setUserType(LoginKey.MANAGER);
    }

    public void managerOperator() {
        boolean exit = false;
        while (!exit) {
            boolean back = false;
            switch (managerMenu()) {
                case "1": //密码管理
                    while (!back) {
                        switch (managerPasswordMenu()) {
                            case "1": //修改自身密码
                                Tool.resetPassword(this);
                                break;
                            case "2": //重置某个前台的密码
                                Tool.resetLowLevelPassword(this);
                                break;
                            case "0": //返回上一级
                                back = true;
                                break;
                            default:
                                System.out.println("输入错误，请重新输入：");
                        }
                    }
                    break;
                case "2": //影片管理
                    while (!back) {
                        switch (filmManagementMenu()) {
                            case "1": //列出所有正在上映的影片
                                showAllShowFilms();
                                break;
                            case "2": //添加影片
                                addFilm();
                                break;
                            case "3": //修改电影信息
                                changeFilmInformation();
                                break;
                            case "4": //删除影片
                                deleteFilm();
                                break;
                            case "5": //查询影片
                                queryFilm();
                                break;
                            case "0": //返回上一级
                                back = true;
                                break;
                            default:
                                System.out.println("输入错误，请重新输入：");
                        }
                    }
                    break;
                case "3": //排片管理
                    while (!back) {
                        switch (filmScheduleManagementMenu()) {
                            case "1": //增加场次
                                addSchedule();
                                break;
                            case "2": //修改场次
                                changeSchedule();
                                break;
                            case "3": //删除场次
                                deleteSchedule();
                                break;
                            case "4": //列出所有场次
                                showAllSchedule();
                                break;
                            case "5": //自动排片
                                autoSchedule();
                                break;
                            case "0": //返回上一级
                                back = true;
                                break;
                            default:
                                System.out.println("输入错误，请重新输入：");
                        }
                    }
                    break;
                case "4": //查看销售数据
                    viewSalesData();
                    break;
                case "0": //退出登录
                    System.out.println("\n-> 退出登录\n");
                    exit = true;
                    break;
                default:
                    System.out.println("输入错误，请重新输入：");
            }
        }
    }

    private void showAllShowFilms() {
        System.out.println("已上映的电影信息如下：");
        for (Film film : CinemaSystem.filmsList) {
            System.out.print("电影名：" + film.getName());
            System.out.println("\t" + "导演：" + film.getDirector());
            System.out.println("\t" + "主演：" + film.getMainCharacter());
            System.out.println("\t" + "剧情简介：" + film.getSynopsis());
            System.out.println("\t" + "时长：" + film.getLength());
            System.out.println("\t" + "评分：" + film.getScore());
            System.out.println("\t" + "基础价格：" + film.getBasicPrice());
            System.out.print("\n");
        }
    }

    private void addFilm() {
        String[] newFilm = new String[4];
        int filmScore;
        int filmLength;
        int basicPrice;
        System.out.println("请输入新增电影的各项信息：");
        System.out.print("片名：");
        newFilm[0] = input.next();
        System.out.print("导演：");
        newFilm[1] = input.next();
        System.out.print("主演：");
        newFilm[2] = input.next();
        System.out.print("剧情简介：");
        newFilm[3] = input.next();
        System.out.print("时长： (单位：min)");
        filmLength = input.nextInt();
        System.out.print("评分： (0 - 10分)");
        filmScore = input.nextInt();
        System.out.print("电影播放基础价格：");
        basicPrice = input.nextInt();

        CinemaSystem.filmsList.add(new Film(newFilm[0], newFilm[1], newFilm[2], newFilm[3], filmLength, filmScore, basicPrice));
        System.out.println("添加电影成功！返回上一级...");
    }

    private void changeFilmInformation() {
        if (CinemaSystem.filmsList.isEmpty()) {
            System.out.println("当前没有电影可修改！返回上一级...");
            return;
        }
        System.out.print("请输入要修改的电影名称（输入0返回上一级）：");
        String filmName = input.next();
        if (filmName.equals("0")) {
            System.out.println("返回上一级...");
            return;
        }

        Film targetFilm = null;
        for (Film film : CinemaSystem.filmsList) {
            if (film.getName().equalsIgnoreCase(filmName)) { //忽略大小写
                targetFilm = film;
                break;
            }
        }
        if (targetFilm == null) {
            System.out.println("未找到电影《" + filmName + "》！");
            return;
        }

        // 显示当前信息并修改
        System.out.println("\n当前电影信息：");
        System.out.println("1. 片名: " + targetFilm.getName());
        System.out.println("2. 导演: " + targetFilm.getDirector());
        System.out.println("3. 主演: " + targetFilm.getDirector());
        System.out.println("4. 剧情简介: " + targetFilm.getSynopsis());
        System.out.println("5. 时长: " + targetFilm.getLength() + "min");
        System.out.println("6. 评分: " + targetFilm.getScore() + "分");
        System.out.println("7. 基础价格: ¥" + targetFilm.getBasicPrice());

        System.out.print("\n请输入要修改的项编号（1-7，输入0放弃修改）：");
        int choice = input.nextInt();
        switch (choice) {
            case 0:
                System.out.println("放弃修改，返回上一级...");
                break;
            case 1:
                System.out.print("新片名：");
                targetFilm.setName(input.nextLine());
                break;
            case 2:
                System.out.print("新导演：");
                targetFilm.setDirector(input.nextLine());
                break;
            case 3:
                System.out.print("新主演：");
                targetFilm.setMainCharacter(input.nextLine());
                break;
            case 4:
                System.out.print("新剧情简介：");
                targetFilm.setSynopsis(input.nextLine());
                break;
            case 5:
                System.out.print("新时长（min）：");
                targetFilm.setLength(input.nextInt());
                break;
            case 6:
                System.out.print("新评分（0-10）：");
                int score = input.nextInt();
                if (score >= 0 && score <= 10) {
                    targetFilm.setScore(score);
                } else {
                    System.out.println("评分无效（必须0-10）！");
                }
                break;
            case 7:
                System.out.print("新基础价格：");
                targetFilm.setBasicPrice(input.nextInt());
                break;
            default:
                System.out.println("无效输入！");
        }

        if (choice > 0 && choice <= 7) {
            System.out.println("《" + targetFilm.getName() + "》修改成功！");
        }
    }

    private void deleteFilm() {
        if (CinemaSystem.filmsList.isEmpty()) {
            System.out.println("当前没有电影可删除！返回上一级...");
            return;
        }
        System.out.print("请输入要删除的电影名称（输入0返回上一级）：");
        String filmName = input.next();
        if (filmName.equals("0")) {
            System.out.println("返回上一级...");
            return;
        }

        Film targetFilm = null;
        for (Film film : CinemaSystem.filmsList) {
            if (film.getName().equalsIgnoreCase(filmName)) { //忽略大小写
                targetFilm = film;
                break;
            }
        }
        if (targetFilm == null) {
            System.out.println("未找到电影《" + filmName + "》！");
            return;
        }

        // 检查电影是否被排片
        boolean isScheduled = false;
        if (CinemaSystem.schedules != null) {
            for (Schedule schedule : CinemaSystem.schedules) {
                if (schedule.getFilm().getName().equalsIgnoreCase(filmName)) {
                    isScheduled = true;
                    break;
                }
            }
        }
        if (isScheduled) {
            System.out.println("《" + filmName + "》已被排片，无法删除！");
            return;
        }
        //删除操作
        System.out.println("-----------------------");
        System.out.print("确认删除电影《" + targetFilm.getName() + "》吗？(Y/N  输入大写字母): ");
        String confirm = input.nextLine().trim().toUpperCase();

        if (confirm.equals("Y")) {
            CinemaSystem.filmsList.remove(targetFilm);
            System.out.println("《" + filmName + "》已成功删除！");
        } else {
            System.out.println("已取消删除操作。");
        }
    }

    private void queryFilm() {
        if (CinemaSystem.filmsList.isEmpty()) {
            System.out.println("当前没有电影可查找！返回上一级...");
            return;
        }

        System.out.println("\n-> 电影查询界面");
        System.out.println("1. 按电影名称查询");
        System.out.println("2. 按导演查询");
        System.out.println("3. 按主演查询");
        System.out.println("4. 组合查询（名称+导演+主演）");
        System.out.println("0. 返回上一级");
        System.out.print("请选择查询方式：");

        int choice = input.nextInt();
        input.nextLine(); // 消耗换行符

        List<Film> resultFilms = new ArrayList<>();

        switch (choice) {
            case 0:
                System.out.println("返回上一级...");
                return;

            case 1:
                // 按名称查询
                System.out.print("请输入电影名称：");
                String name = input.nextLine();
                if (name.trim().isEmpty()) {
                    System.out.println("输入不能为空！");
                    return;
                }
                for (Film film : CinemaSystem.filmsList) {
                    if (film.getName().equalsIgnoreCase(name)) {
                        resultFilms.add(film);
                    }
                }
                break;

            case 2:
                // 按导演查询
                System.out.print("请输入导演姓名：");
                String director = input.nextLine();
                if (director.trim().isEmpty()) {
                    System.out.println("输入不能为空！");
                    return;
                }
                for (Film film : CinemaSystem.filmsList) {
                    if (film.getDirector().toLowerCase().contains(director.toLowerCase())) {
                        resultFilms.add(film);
                    }
                }
                break;

            case 3:
                // 按主演查询
                System.out.print("请输入主演姓名：");
                String actor = input.nextLine();
                if (actor.trim().isEmpty()) {
                    System.out.println("输入不能为空！");
                    return;
                }
                for (Film film : CinemaSystem.filmsList) {
                    if (film.getDirector().toLowerCase().contains(actor.toLowerCase())) {
                        resultFilms.add(film);
                    }
                }
                break;

            case 4:
                // 组合查询
                System.out.print("请输入电影名称（可留空）：");
                String comboName = input.nextLine();

                System.out.print("请输入导演姓名（可留空）：");
                String comboDirector = input.nextLine();

                System.out.print("请输入主演姓名（可留空）：");
                String comboActor = input.nextLine();

                // 如果所有条件都为空，则提示用户
                if (comboName.trim().isEmpty() && comboDirector.trim().isEmpty() && comboActor.trim().isEmpty()) {
                    System.out.println("至少需要输入一个查询条件！");
                    return;
                }

                for (Film film : CinemaSystem.filmsList) {
                    boolean nameMatch = comboName.trim().isEmpty() ||
                            film.getName().equalsIgnoreCase(comboName);
                    boolean directorMatch = comboDirector.trim().isEmpty() ||
                            film.getDirector().toLowerCase().contains(comboDirector.toLowerCase());
                    boolean actorMatch = comboActor.trim().isEmpty() ||
                            film.getDirector().toLowerCase().contains(comboActor.toLowerCase());

                    if (nameMatch && directorMatch && actorMatch) {
                        resultFilms.add(film);
                    }
                }
                break;

            default:
                System.out.println("无效的选择！");
                return;
        }

        // 显示查询结果
        if (resultFilms.isEmpty()) {
            System.out.println("未找到符合条件的电影！");
        } else {
            System.out.println("\n找到 " + resultFilms.size() + " 部符合条件的电影：");
            System.out.println("==============================================");

            for (int i = 0; i < resultFilms.size(); i++) {
                Film film = resultFilms.get(i);
                System.out.println("【电影 " + (i + 1) + "】");
                System.out.println("1. 片名: " + film.getName());
                System.out.println("2. 导演: " + film.getDirector());
                System.out.println("3. 主演: " + film.getDirector());
                System.out.println("4. 剧情简介: " + film.getSynopsis());
                System.out.println("5. 时长: " + film.getLength() + "min");
                System.out.println("6. 评分: " + film.getScore() + "分");
                System.out.println("7. 基础价格: ¥" + film.getBasicPrice());
                System.out.println("----------------------------------------------");
            }
        }
    }

    private void addSchedule() {
        //1.选择电影
        System.out.println("当前可排片电影：");
        for (int i = 0; i < CinemaSystem.filmsList.size(); i++) {
            Film f = CinemaSystem.filmsList.get(i);
            System.out.printf("%d. 《%s》（%d分钟）¥%.1f\n",
                    i+1, f.getName(), f.getLength(), (double)f.getBasicPrice());
        }
        System.out.print("-> 选择电影编号：");
        int filmIdx = input.nextInt() - 1;
        Film film = CinemaSystem.filmsList.get(filmIdx);

        //2.选择影厅
        System.out.println("可选影厅及服务费：");
        for (int i = 0; i < CinemaSystem.ScreeningHalls.size(); i++) {
            ScreeningHall h = CinemaSystem.ScreeningHalls.get(i);
            System.out.printf("%d. %s（服务费+¥%d）\n", i+1, h.getType(), h.getServiceFee());
        }
        System.out.print("-> 选择影厅编号：");
        int hallIdx = input.nextInt() - 1;
        ScreeningHall hall = CinemaSystem.ScreeningHalls.get(hallIdx);

        //3.输入时间
        System.out.print("-> 输入放映时间（格式：yyyy-MM-dd HH:mm）：");
        String timeStr = input.next();

        //进行异常处理
        try {
            Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(timeStr);

            // 4.检查冲突
            if (isScheduleConflict(hall, startTime, film.getLength())) {
                System.out.println("该时段已有排片！无法进行操作！返回上一级...");
                return;
            }

            // 5.创建排片
            Schedule newSchedule = new Schedule(film, hall, startTime);
            CinemaSystem.schedules.add(newSchedule); //创建操作
            System.out.printf("已添加排片：%s《%s》¥%.1f\n",
                    hall.getType(), film.getName(), newSchedule.getFinalPrice());
        } catch (Exception e) {
            System.out.println("时间格式无效！");
        }
    }

    private boolean isScheduleConflict(ScreeningHall hall, Date newStart, int durationMin) { //检查是否排片
        long durationMs = (long)durationMin * 60 * 1000;
        Date newEnd = new Date(newStart.getTime() + durationMs);

        for (Schedule s : CinemaSystem.schedules) {
            if (s.getHall().equals(hall)) {
                Date existingStart = s.getStartTime();
                Date existingEnd = s.getEndTime();
                // 检查时间段是否重叠
                if (newStart.before(existingEnd) && newEnd.after(existingStart)) {
                    return true;
                }
            }
        }
        return false;
    }

    private void changeSchedule() {
        if (CinemaSystem.schedules.isEmpty()) {
            System.out.println("当前没有排片可修改！返回上一级...");
            return;
        }

        // 显示所有排片
        System.out.println("\n=== 当前所有排片 ===");
        for (int i = 0; i < CinemaSystem.schedules.size(); i++) {
            Schedule schedule = CinemaSystem.schedules.get(i);
            Film film = schedule.getFilm();
            ScreeningHall hall = schedule.getHall();

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String timeStr = sdf.format(schedule.getStartTime());

            System.out.printf("%d. %s《%s》 %s ¥%.1f\n",
                    i + 1, hall.getType(), film.getName(), timeStr, schedule.getFinalPrice());
        }

        System.out.print("-> 选择要修改的排片编号（输入0返回上一级）：");
        int scheduleIdx = input.nextInt() - 1;
        input.nextLine(); // 消耗换行符

        if (scheduleIdx == -1) {
            System.out.println("返回上一级...");
            return;
        }

        if (scheduleIdx < 0 || scheduleIdx >= CinemaSystem.schedules.size()) {
            System.out.println("无效的排片编号！");
            return;
        }

        Schedule targetSchedule = CinemaSystem.schedules.get(scheduleIdx);

        System.out.println("\n=== 修改排片信息 ===");
        System.out.println("当前排片信息：");
        System.out.println("1. 电影: 《" + targetSchedule.getFilm().getName() + "》");
        System.out.println("2. 影厅: " + targetSchedule.getHall().getType());
        System.out.println("3. 时间: " + new SimpleDateFormat("yyyy-MM-dd HH:mm").format(targetSchedule.getStartTime()));
        System.out.println("4. 最终价格: ¥" + targetSchedule.getFinalPrice());

        System.out.println("\n请选择要修改的内容：");
        System.out.println("1. 修改电影");
        System.out.println("2. 修改影厅");
        System.out.println("3. 修改时间");
        System.out.println("4. 修改所有信息");
        System.out.println("0. 取消修改");
        System.out.print("-> 请选择：");

        int choice = input.nextInt();
        input.nextLine(); // 消耗换行符

        switch (choice) {
            case 0:
                System.out.println("取消修改...");
                return;

            case 1:
                // 修改电影
                modifyFilm(targetSchedule);
                break;

            case 2:
                // 修改影厅
                modifyHall(targetSchedule);
                break;

            case 3:
                // 修改时间
                modifyTime(targetSchedule);
                break;

            case 4:
                // 修改所有信息
                modifyAll(targetSchedule);
                break;

            default:
                System.out.println("无效的选择！");
                return;
        }

        System.out.println("排片信息修改成功！");
    }

    // 修改电影
    private void modifyFilm(Schedule schedule) {
        System.out.println("\n当前可排片电影：");
        for (int i = 0; i < CinemaSystem.filmsList.size(); i++) {
            Film f = CinemaSystem.filmsList.get(i);
            System.out.printf("%d. 《%s》（%d分钟）¥%.1f\n",
                    i + 1, f.getName(), f.getLength(), (double) f.getBasicPrice());
        }
        System.out.print("-> 选择新的电影编号：");
        int filmIdx = input.nextInt() - 1;

        if (filmIdx < 0 || filmIdx >= CinemaSystem.filmsList.size()) {
            System.out.println("无效的电影编号！");
            return;
        }

        Film newFilm = CinemaSystem.filmsList.get(filmIdx);
        schedule.setFilm(newFilm);

        // 重新计算最终价格
        schedule.setFinalPrice(newFilm.getBasicPrice() + schedule.getHall().getServiceFee());
    }

    // 修改影厅
    private void modifyHall(Schedule schedule) {
        System.out.println("\n可选影厅及服务费：");
        for (int i = 0; i < CinemaSystem.ScreeningHalls.size(); i++) {
            ScreeningHall h = CinemaSystem.ScreeningHalls.get(i);
            System.out.printf("%d. %s（服务费+¥%d）\n", i + 1, h.getType(), h.getServiceFee());
        }
        System.out.print("-> 选择新的影厅编号：");
        int hallIdx = input.nextInt() - 1;

        if (hallIdx < 0 || hallIdx >= CinemaSystem.ScreeningHalls.size()) {
            System.out.println("无效的影厅编号！");
            return;
        }

        ScreeningHall newHall = CinemaSystem.ScreeningHalls.get(hallIdx);

        // 检查时间冲突（排除自身）
        if (isScheduleConflict(newHall, schedule.getStartTime(), schedule.getFilm().getLength(), schedule)) {
            System.out.println("该时段已有其他排片！无法修改！");
            return;
        }

        schedule.setHall(newHall);

        // 重新计算最终价格
        schedule.setFinalPrice(schedule.getFilm().getBasicPrice() + newHall.getServiceFee());
    }

    // 修改时间
    private void modifyTime(Schedule schedule) {
        System.out.print("-> 输入新的放映时间（格式：yyyy-MM-dd HH:mm）：");
        String timeStr = input.next();
        input.nextLine(); // 消耗换行符

        try {
            Date newStartTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(timeStr);

            // 检查时间冲突（排除自身）
            if (isScheduleConflict(schedule.getHall(), newStartTime, schedule.getFilm().getLength(), schedule)) {
                System.out.println("该时段已有其他排片！无法修改！");
                return;
            }

            schedule.setStartTime(newStartTime);
        } catch (Exception e) {
            System.out.println("时间格式无效！");
        }
    }

    // 修改所有信息
    private void modifyAll(Schedule schedule) {
        modifyFilm(schedule);
        modifyHall(schedule);
        modifyTime(schedule);
    }

    // 检查时间冲突（重载方法，排除自身）
    private boolean isScheduleConflict(ScreeningHall hall, Date startTime, int filmLength, Schedule excludeSchedule) {
        Date endTime = new Date(startTime.getTime() + (long) filmLength * 60 * 1000);

        for (Schedule existingSchedule : CinemaSystem.schedules) {
            // 排除自身
            if (existingSchedule.equals(excludeSchedule)) {
                continue;
            }

            // 检查同一影厅
            if (existingSchedule.getHall().equals(hall)) {
                Date existingStart = existingSchedule.getStartTime();
                Date existingEnd = new Date(existingStart.getTime() +
                        (long) existingSchedule.getFilm().getLength() * 60 * 1000);

                // 检查时间重叠
                if (startTime.before(existingEnd) && endTime.after(existingStart)) {
                    return true;
                }
            }
        }
        return false;
    }

    private void deleteSchedule() {
        showAllSchedule();
        if (CinemaSystem.schedules.isEmpty()) return;

        System.out.print("请输入要删除的排片序号：");
        int idx = input.nextInt() - 1;
        if (idx >= 0 && idx < CinemaSystem.schedules.size()) {
            Schedule s = CinemaSystem.schedules.remove(idx); //删除排片操作
            System.out.printf("✔ 已删除：%s《%s》\n",
                    s.getHall().getType(), s.getFilm().getName());
        } else {
            System.out.println("【错误】无效序号！");
        }
    }

    private void showAllSchedule() {
        if (CinemaSystem.schedules.isEmpty()) {
            System.out.println("当前无排片记录");
            return;
        }

        System.out.println("当前所有排片：");
        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd HH:mm");
        for (Schedule s : CinemaSystem.schedules) {
            System.out.printf(
                    "%-8s | %-10s | %s-%s | 《%s》 | ¥%.1f\n",
                    s.getHall().getType(),
                    sdf.format(s.getStartTime()),
                    sdf.format(s.getStartTime()),
                    sdf.format(s.getEndTime()),
                    s.getFilm().getName(),
                    s.getFinalPrice()
            );
        }
    }

    private void autoSchedule() {
        if (CinemaSystem.filmsList.isEmpty()) {
            System.out.println("当前没有电影可排片！返回上一级...");
            return;
        }

        if (CinemaSystem.ScreeningHalls.isEmpty()) {
            System.out.println("当前没有可用影厅！返回上一级...");
            return;
        }

        System.out.println("\n-> 自动排片界面");
        System.out.print("请输入要排片的起始日期（格式：yyyy-MM-dd）：");
        String startDateStr = input.next();
        input.nextLine();

        System.out.print("请输入排片天数（1-7）：");
        int days = input.nextInt();

        if (days < 1 || days > 7) {
            System.out.println("天数必须在1-7之间！");
            return;
        }

        try {
            Date startDate = new SimpleDateFormat("yyyy-MM-dd").parse(startDateStr);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);

            //高评分优先
            List<Film> sortedFilms = new ArrayList<>(CinemaSystem.filmsList);
            sortedFilms.sort((f1, f2) -> Double.compare(f2.getScore(), f1.getScore()));

            int totalSchedules = 0;

            for (int day = 0; day < days; day++) {
                Date currentDate = calendar.getTime();
                int schedulesToday = scheduleForDay(sortedFilms, currentDate);
                totalSchedules += schedulesToday;

                System.out.printf("第%d天安排了%d个场次\n", day + 1, schedulesToday);
                calendar.add(Calendar.DAY_OF_MONTH, 1); // 下一天
            }

            System.out.printf("\n自动排片完成！共安排了%d个场次\n", totalSchedules);

        } catch (Exception e) {
            System.out.println("日期格式无效！");
        }
    }

    private int scheduleForDay(List<Film> films, Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

        //判断是否是周末
        boolean isWeekend = (dayOfWeek == Calendar.SATURDAY || dayOfWeek == Calendar.SUNDAY);

        int schedulesCount = 0;
        //上午、下午、晚上的时间段
        String[] timeSlots = {"09:00", "11:00", "13:00", "15:00", "17:00", "19:00", "21:00"};
        // 周末和晚上为黄金时间段
        int maxSchedules = isWeekend ? timeSlots.length : timeSlots.length - 2;

        // 按影厅安排场次
        for (ScreeningHall hall : CinemaSystem.ScreeningHalls) {
            int hallSchedules = 0;

            for (int i = 0; i < maxSchedules && hallSchedules < (isWeekend ? 5 : 4); i++) {
                String timeStr = timeSlots[i];

                try {
                    String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);
                    String fullTimeStr = dateStr + " " + timeStr;
                    Date startTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(fullTimeStr);

                    Film bestFilm = selectBestFilmForTimeSlot(films, timeStr, isWeekend);

                    if (bestFilm != null && !isScheduleConflict(hall, startTime, bestFilm.getLength())) {
                        Schedule newSchedule = new Schedule(bestFilm, hall, startTime);
                        CinemaSystem.schedules.add(newSchedule);
                        schedulesCount++;
                        hallSchedules++;

                        System.out.printf("安排：%s %s《%s》\n",
                                new SimpleDateFormat("MM-dd HH:mm").format(startTime),
                                hall.getType(), bestFilm.getName());
                    }
                } catch (Exception e) {
                    //时间错误，进行下一个
                }
            }
        }
        return schedulesCount;
    }

    private Film selectBestFilmForTimeSlot(List<Film> films, String timeStr, boolean isWeekend) {
        //判断是否是黄金时间段（晚上或周末下午晚上）
        boolean isPrimeTime = isPrimeTime(timeStr, isWeekend);

        Film selectedFilm = null;
        double bestScore = -1;

        for (Film film : films) {
            // 跳过已经安排过多的电影
            if (getFilmScheduleCount(film) > 3) {
                continue;
            }
            // 黄金时间段优先安排高评分电影
            if (isPrimeTime) {
                if (film.getScore() > bestScore) {
                    bestScore = film.getScore();
                    selectedFilm = film;
                }
            } else {
                if (selectedFilm == null || film.getScore() > selectedFilm.getScore()) {
                    selectedFilm = film;
                }
            }
        }
        return selectedFilm;
    }

    private boolean isPrimeTime(String timeStr, boolean isWeekend) {
        String[] parts = timeStr.split(":");
        int hour = Integer.parseInt(parts[0]);
        // 周末：全天都是较好的时间段，下午和晚上是黄金段
        // 工作日：晚上17点以后是黄金时间段
        if (isWeekend) {
            return hour >= 14; // 周末下午和晚上
        } else {
            return hour >= 17; // 工作日晚上
        }
    }

    private int getFilmScheduleCount(Film film) {
        int count = 0;
        for (Schedule schedule : CinemaSystem.schedules) {
            if (schedule.getFilm().equals(film)) {
                count++;
            }
        }
        return count;
    }

    private String managerMenu() {
        System.out.println("-------权限：" + getUserType() +
                " ----- " + "用户名：" + getUserName() + "-------");
        System.out.println("1. 密码管理");
        System.out.println("2. 影片管理");
        System.out.println("3. 排片管理");
        System.out.println("4. 查看销售数据");
        System.out.println("0. 退出登录");

        System.out.println("请选择：");
        String choice;
        boolean right;
        do {
            choice = input.next();
            right = choice.equals("1") || choice.equals("2") || choice.equals("3") ||
                    choice.equals("4") || choice.equals("0");
            if (!right) System.out.println("输入错误，请重新输入：");
        } while (!right);
        return choice;
    }

    private String managerPasswordMenu() {
        System.out.println("-------权限：" + getUserType() +
                " ----- " + "用户名：" + getUserName() + "-------");
        System.out.println("1. 修改自身密码");
        System.out.println("2. 重置指定前台用户的密码");
        System.out.println("0. 返回上一级");
        System.out.println("请选择：");
        String choice;
        boolean right;
        do {
            choice = input.next();
            right = choice.equals("1") || choice.equals("2") || choice.equals("0");
            if (!right) System.out.println("输入错误，请重新输入：");
        } while (!right);
        return choice;
    }

    private String filmManagementMenu() {
        System.out.println("-------权限：" + getUserType() +
                " ----- " + "用户名：" + getUserName() + "-------");
        System.out.println("1. 列出所有正在上映的影片");
        System.out.println("2. 添加影片");
        System.out.println("3. 修改指定电影的信息");
        System.out.println("4. 删除影片");
        System.out.println("5. 查询指定影片");
        System.out.println("0. 返回上一级");
        System.out.println("请选择：");
        String choice;
        boolean right;
        do {
            choice = input.next();
            right = choice.equals("1") || choice.equals("2") || choice.equals("3") ||
                    choice.equals("4") || choice.equals("5") || choice.equals("0");
            if (!right) System.out.println("输入错误，请重新输入：");
        } while (!right);
        return choice;
    }

    private String filmScheduleManagementMenu() {
        System.out.println("-------权限：" + getUserType() +
                " ----- " + "用户名：" + getUserName() + "-------");
        System.out.println("1. 增加场次");
        System.out.println("2. 修改场次");
        System.out.println("3. 删除场次");
        System.out.println("4. 列出所有场次");
        System.out.println("5. 自动排片");
        System.out.println("0. 返回上一级");
        System.out.println("请选择：");
        String choice;
        boolean right;
        do {
            choice = input.next();
            right = choice.equals("1") || choice.equals("2") || choice.equals("3") ||
                    choice.equals("4") || choice.equals("5") || choice.equals("0");
            if (!right) System.out.println("输入错误，请重新输入：");
        } while (!right);
        return choice;
    }

    private void viewSalesData() {
        System.out.println("-------权限：" + getUserType() +
                " ----- " + "用户名：" + getUserName() + "-------");
        System.out.println("1. 当日数据");
        System.out.println("2. 当周数据");
        System.out.println("3. 当月数据");
        System.out.println("0. 返回上一级");
        System.out.print("请选择：");

        String choice = input.next();
        boolean loop;
        do {
            loop = false;
            switch (choice) {
                case "1":
                    showDailySalesData();
                    break;
                case "2":
                    showWeeklySalesData();
                    break;
                case "3":
                    showMonthlySalesData();
                    break;
                case "0":
                    System.out.println("返回上一级...");
                    return;
                default:
                    System.out.print("输入错误，请重新选择：");
                    choice = input.next();
                    loop = true;
            }
        } while(loop);
    }

    // 显示当日销售数据
    private void showDailySalesData() {
        Date today = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String todayStr = sdf.format(today);

        double totalRevenue = 0;
        int totalTickets = 0;
        Map<String, Integer> filmSales = new HashMap<>(); // 电影销售统计
        Map<String, Integer> hallSales = new HashMap<>(); // 影厅销售统计

        for (Schedule schedule : CinemaSystem.schedules) {
            Date scheduleDate = schedule.getStartTime();
            String scheduleDateStr = sdf.format(scheduleDate);

            if (scheduleDateStr.equals(todayStr)) {
                int soldCount = schedule.getSoldSeats().size();
                double revenue = soldCount * schedule.getFinalPrice();

                totalRevenue += revenue;
                totalTickets += soldCount;

                // 统计电影销售
                String filmName = schedule.getFilm().getName();
                filmSales.put(filmName, filmSales.getOrDefault(filmName, 0) + soldCount);

                // 统计影厅销售
                String hallType = schedule.getHall().getType();
                hallSales.put(hallType, hallSales.getOrDefault(hallType, 0) + soldCount);
            }
        }

        displaySalesData("当日", todayStr, totalRevenue, totalTickets, filmSales, hallSales);
    }

    // 显示当周销售数据
    private void showWeeklySalesData() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 设置为本周周一
        Date weekStart = cal.getTime();
        cal.add(Calendar.DAY_OF_WEEK, 6); // 设置为本周周日
        Date weekEnd = cal.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String weekRange = sdf.format(weekStart) + " 至 " + sdf.format(weekEnd);

        double totalRevenue = 0;
        int totalTickets = 0;
        Map<String, Integer> filmSales = new HashMap<>();
        Map<String, Integer> hallSales = new HashMap<>();

        for (Schedule schedule : CinemaSystem.schedules) {
            Date scheduleDate = schedule.getStartTime();
            if (!scheduleDate.before(weekStart) && !scheduleDate.after(weekEnd)) {
                int soldCount = schedule.getSoldSeats().size();
                double revenue = soldCount * schedule.getFinalPrice();

                totalRevenue += revenue;
                totalTickets += soldCount;

                String filmName = schedule.getFilm().getName();
                filmSales.put(filmName, filmSales.getOrDefault(filmName, 0) + soldCount);

                String hallType = schedule.getHall().getType();
                hallSales.put(hallType, hallSales.getOrDefault(hallType, 0) + soldCount);
            }
        }

        displaySalesData("当周", weekRange, totalRevenue, totalTickets, filmSales, hallSales);
    }

    // 显示当月销售数据
    private void showMonthlySalesData() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_MONTH, 1); // 设置为本月第一天
        Date monthStart = cal.getTime();
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); // 设置为本月最后一天
        Date monthEnd = cal.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        String monthStr = sdf.format(monthStart);

        double totalRevenue = 0;
        int totalTickets = 0;
        Map<String, Integer> filmSales = new HashMap<>();
        Map<String, Integer> hallSales = new HashMap<>();

        for (Schedule schedule : CinemaSystem.schedules) {
            Date scheduleDate = schedule.getStartTime();
            if (!scheduleDate.before(monthStart) && !scheduleDate.after(monthEnd)) {
                int soldCount = schedule.getSoldSeats().size();
                double revenue = soldCount * schedule.getFinalPrice();

                totalRevenue += revenue;
                totalTickets += soldCount;

                String filmName = schedule.getFilm().getName();
                filmSales.put(filmName, filmSales.getOrDefault(filmName, 0) + soldCount);

                String hallType = schedule.getHall().getType();
                hallSales.put(hallType, hallSales.getOrDefault(hallType, 0) + soldCount);
            }
        }

        displaySalesData("当月", monthStr, totalRevenue, totalTickets, filmSales, hallSales);
    }

    // 显示销售数据报表
    private void displaySalesData(String periodType, String periodRange,
                                  double totalRevenue, int totalTickets,
                                  Map<String, Integer> filmSales, Map<String, Integer> hallSales) {
        System.out.println("\n=== " + periodType + "销售数据报表 (" + periodRange + ") ===");
        System.out.println("==============================================");
        System.out.printf("总票房收入: ¥%.2f\n", totalRevenue);
        System.out.printf("总售票数量: %d 张\n", totalTickets);
        System.out.printf("平均票价: ¥%.2f\n", totalTickets > 0 ? totalRevenue / totalTickets : 0);
        System.out.println("----------------------------------------------");

        // 电影销售排名
        if (!filmSales.isEmpty()) {
            System.out.println("电影销售排名:");
            filmSales.entrySet().stream()
                    .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                    .forEach(entry -> System.out.printf("  《%s》: %d 张\n", entry.getKey(), entry.getValue()));
            System.out.println("----------------------------------------------");
        }

        // 影厅销售排名
        if (!hallSales.isEmpty()) {
            System.out.println("影厅销售排名:");
            hallSales.entrySet().stream()
                    .sorted((e1, e2) -> e2.getValue().compareTo(e1.getValue()))
                    .forEach(entry -> System.out.printf("  %s: %d 张\n", entry.getKey(), entry.getValue()));
            System.out.println("----------------------------------------------");
        }

        // 上座率统计（需要 ScreeningHall 有 getCapacity() 方法）
        if (totalTickets > 0) {
            System.out.println("场次统计:");
            Map<String, int[]> scheduleStats = new HashMap<>(); // 影厅: [总场次, 总座位数]

            for (Schedule schedule : CinemaSystem.schedules) {
                String hallType = schedule.getHall().getType();
                int[] stats = scheduleStats.getOrDefault(hallType, new int[2]);
                stats[0]++; // 场次计数
                stats[1] += schedule.getHall().getCapacity(); // 总座位数
                scheduleStats.put(hallType, stats);
            }

            for (Map.Entry<String, int[]> entry : scheduleStats.entrySet()) {
                int totalSeats = entry.getValue()[1];
                int soldSeats = hallSales.getOrDefault(entry.getKey(), 0);
                double occupancyRate = totalSeats > 0 ? (double) soldSeats / totalSeats * 100 : 0;
                System.out.printf("  %s: %d场, 上座率: %.1f%%\n",
                        entry.getKey(), entry.getValue()[0], occupancyRate);
            }
        }
        System.out.println("==============================================");
    }
}
